package logica_de_presentacion;
import javax.swing.JFileChooser;
import javax.swing.JInternalFrame;
import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.JTextArea;

import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.io.File;

public class FileDialogProgram extends JInternalFrame implements ActionListener {

	
    /**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private JTextArea tracker; 
	private JPanel optPanel;
	private JFileChooser fileDialog;
    
    private JButton openButton;
    private String path;

    public FileDialogProgram()
    { 
    	super("Elegir la imagen que desea",true,true,true,true);
        this.setSize(500,300);
        path=null;
 
        this.setLayout(new BorderLayout());
        
        fileDialog = new JFileChooser();
        tracker = new JTextArea("Imagen a selecionar:");
        tracker.setVisible(true);
        this.add(tracker, BorderLayout.NORTH);
        
        optPanel = new JPanel();
        optPanel.setLayout(new GridLayout(1,2));
        
        
        this.add(optPanel,BorderLayout.SOUTH);

        openButton = new JButton("Buscar Archivo");
        openButton.addActionListener(this);
        optPanel.add(openButton);       
        
        this.setVisible(true);
    }
    
    private void openDialog()
    {
        int openChoice = fileDialog.showOpenDialog(this);
        
        logChoice(openChoice);
        
        if (openChoice == JFileChooser.APPROVE_OPTION)
        {
            File openFile = fileDialog.getSelectedFile();
            tracker.append("\nEl archivo es " + openFile.getName());
            tracker.append("\nEl path es  " + openFile.getPath());
            path=openFile.getPath();
            this.dispose();
        }
            
    }
    
    private void logChoice(int choice)
    {
        switch (choice)
        {
            //The user pressed cancel button
            case JFileChooser.CANCEL_OPTION:
                tracker.append("\nCANCELADO");
                break;
                
            //The user pressed the open/save button
            case JFileChooser.APPROVE_OPTION:
                tracker.append("\nAPROVADO");
                break;
                
            //The user dismissed the dialog without pressing a button
            case JFileChooser.ERROR_OPTION:
                tracker.append("\nERROR ");
                break;
        }
    }

	@Override
	public void actionPerformed(ActionEvent e) {
		JButton botonPulsado=(JButton) e.getSource();
		if(botonPulsado==openButton){
			openDialog();
		}		
	}
	
	public String getPath(){
		return path;
	}
}
